type TargetContext = '_self' | '_parent' | '_blank' | '_top';
import { Message } from '@arco-design/web-vue';
import ajax from '../api/ajax';

export const openWindow = (
  url: string,
  opts?: { target?: TargetContext; [key: string]: any }
) => {
  const { target = '_blank', ...others } = opts || {};
  window.open(
    url,
    target,
    Object.entries(others)
      .reduce((preValue: string[], curValue) => {
        const [key, value] = curValue;
        return [...preValue, `${key}=${value}`];
      }, [])
      .join(',')
  );
};

export const regexUrl = new RegExp(
  '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
  'i'
);

export default null;

export function getAppId() {
  const info = localStorage['user.info'];
  if(!info) return 0;
  return JSON.parse(info).applicationId;
}

export function formatTime (time:string, type:number) {
  if(!time) return '';
  //if(type===1) return time.split('T')[0].slice(2);
  //if(type===2) return time.split('.')[0].replace('T', ' ').slice(2);
  if(type===1) return time.split('T')[0];
  if(type===2) return time.split('.')[0].replace('T', ' ');
  if (type===3) {
    return time.split(":")[0] + ":" + time.split(":")[1];
  }
}

export function number2date(time:number) {
  return new Date(time).toISOString().split('T')[0];
}

export function formatForm(data:any) {
  for(let key in data) {
    if(data[key]===0) data[key] = undefined;
  }
  return data;
}

export function getPostData(pagination:any, formModel:any, sort='') {
  let pdata: any = {
    page: pagination.current,
    pageSize: pagination.pageSize,
    sortProperty: sort,
    sortDirection: 'Desc',
    queryProperties: new Array<any>()
  };
  if(typeof formModel.applicationId==='number') {
    pdata.applicationId = formModel.applicationId;
  }
  for(let key in formModel) {
    let val = formModel[key];
    if(key!=='applicationId' && val) {
      if(val.join) {
        if(val.length && key.includes('Time')) {
          pdata.queryProperties.push({
            propertyName: key,
            propertyValue: `${val[0]} 00:00:01`,
            queryCondition: 'GreaterAndEqual'
          });
          pdata.queryProperties.push({
            propertyName: key,
            propertyValue: `${val[1]} 23:59:59`,
            queryCondition: 'LessAndEqual'
          });
        }
        if(val.length && key.includes('Date')) {
          pdata.queryProperties.push({
            propertyName: key,
            propertyValue: `${val[0]}`,
            queryCondition: 'GreaterAndEqual'
          });
          pdata.queryProperties.push({
            propertyName: key,
            propertyValue: `${val[1]}`,
            queryCondition: 'LessAndEqual'
          });
        }
      } else {
        pdata.queryProperties.push({
          propertyName: key,
          propertyValue: val.toString(),
          queryCondition: key.endsWith('Id')?'Equal':'Like'
        });
      }
    }
  }
  return pdata;
}

export function toTree(arr:Array<any>, idName:string) {
  const deep = function(parentId: number) {
    let aa = arr.filter(a=>a.parentId==parentId);
    aa.forEach(a=>{
      let bb = deep(a[idName]);
      if(bb.length) a.children = bb;
    });
    return aa;
  };
  return deep(0);
}

function $$(sel:string, root:HTMLElement|null=null) {
  return (root||document).querySelectorAll(sel);
}

export function validateForm(form:HTMLElement|null = null, isClear:boolean = false) {
  //arco-input-wrapper arco-input-error
  //arco-select-view-single arco-select-view arco-select-view-size-medium arco-select-view-error
  if(!form) {
    form = document.querySelector('.arco-modal.big');
  }
  const arr1 = $$('.arco-input-error',form);
  arr1.forEach(a=>{
    a.classList.remove('arco-input-error')
  });
  const arr2 = $$('.arco-select-view-error',form);
  arr2.forEach(a=>{
    a.classList.remove('arco-select-view-error')
  });
  if(isClear) return;

  let allright = true;
  const arr = $$('.arco-form-item-label-required-symbol',form);
  arr.forEach(a=>{
    let d = a.closest('.arco-row') as HTMLDivElement;
    let put = d.querySelector('input') as HTMLInputElement;
    if(!put) return;
    if(put.classList.contains('arco-select-view-input')) {
      let val = put.placeholder;
      if(!val && put.nextSibling) {
        let sp = put.nextSibling as HTMLSpanElement;
        val = sp.innerText;
      }
      if(!val && put.previousSibling) {
        let sp = put.previousSibling as HTMLSpanElement;
        val = sp.innerText;
      }
      if(!val || val=='0') {
        allright = false;
        d.querySelector('.arco-select-view')?.classList.add('arco-select-view-error');
      }
    }
    if(put.classList.contains('arco-input') && !put.value) {
      allright = false;
      d.querySelector('.arco-input-wrapper')?.classList.add('arco-input-error');
    }
    if(put.classList.contains('arco-picker-start-time') && !put.value) {
      allright = false;
      d.querySelector('.arco-picker')?.classList.add('arco-input-error');
    }
  });
  if(!allright) {
    Message.warning('带星号内容必填~');
  }
  return allright;
}

export async function exportExcel(api:string, data:any) {
  let fname = await ajax.requestPost<string>(api, data);
  if(!fname) return Message.warning('导出失败 :(');
  
  let uri = `/api/Common/Files/${fname}`;
  let el = document.querySelector('.frm-down');
  if(!el) {
    el = document.createElement('iframe');
    el.setAttribute('style', 'position:absolute;z-index:-1;visibility:hidden;width:1px;');
    document.body.appendChild(el);
  }
  el.setAttribute('src', uri);
}